package com.agrimall.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证过滤器
 */
public class LoginFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        
        String uri = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        String path = uri.substring(contextPath.length());
        
        // 排除登录、注册、静态资源、商品浏览等公开页面
        if (path.equals("/login") || path.equals("/login.jsp")
                || path.equals("/register") || path.equals("/register.jsp")
                || path.startsWith("/static") || path.startsWith("/assets")
                || path.startsWith("/css/") || path.startsWith("/js/") 
                || path.startsWith("/logo/") || path.startsWith("/upload/")
                || path.equals("/") || path.equals("/index.jsp")
                || path.startsWith("/client/product/list") 
                || path.startsWith("/client/product/detail")
                || path.endsWith(".jsp") && (path.contains("/login") || path.contains("/register") || path.contains("/client/product/"))) {
            chain.doFilter(request, response);
            return;
        }
        
        // 客户端页面需要用户登录（商品浏览页面已排除）
        if (path.startsWith("/client/")) {
            Object user = session.getAttribute("user");
            if (user == null) {
                httpResponse.sendRedirect(contextPath + "/login.jsp");
                return;
            }
        }
        
        // 商户端页面需要商户登录
        if (path.startsWith("/merchant/")) {
            Object merchant = session.getAttribute("merchant");
            if (merchant == null) {
                httpResponse.sendRedirect(contextPath + "/login.jsp");
                return;
            }
        }
        
        // 管理员端页面需要管理员登录
        if (path.startsWith("/admin/")) {
            Object admin = session.getAttribute("admin");
            if (admin == null) {
                httpResponse.sendRedirect(contextPath + "/login.jsp");
                return;
            }
        }
        
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy() {
    }
}

